<template>
  <div class="cell-storage-form">
    <h2>细胞出库</h2>

    <!-- 筛选条件 -->
    <div class="filter-bar">
      <div class="filter-item">
        <label>细胞类型</label>
        <select v-model="filters.cellType">
          <option value="">全部</option>
          <option v-for="type in cellTypes" :key="type.id" :value="type.id">
            {{ type.name }}
          </option>
        </select>
      </div>

      <div class="filter-item">
        <label>冰柜名称</label>
        <select v-model="filters.freezer">
          <option value="">全部</option>
          <option v-for="item in freezers" :key="item.id" :value="item.id">
            {{ item.name }} (No.{{ item.number }})
          </option>
        </select>
      </div>

      <div class="filter-item">
        <label>搜索</label>
        <input
          type="text"
          v-model="filters.searchQuery"
          placeholder="输入细胞名称或编号"
        >
      </div>

      <div class="filter-item">
        <button @click="searchCells" class="btn-search">
          <i class="el-icon-search"></i> 搜索
        </button>
      </div>
    </div>

    <!-- 数据表格 -->
    <table class="storage-table">
      <thead>
        <tr>
          <th width="40">
            <input
              type="checkbox"
              v-model="selectAll"
              @change="toggleSelectAll"
            >
          </th>
          <th>细胞编号</th>
          <th>细胞类型</th>
          <th>具体名称</th>
          <th>冰柜名称</th>
          <th>位置</th>
          <th>库存数量</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="cell in paginatedData" :key="cell.id">
          <td>
            <input
              type="checkbox"
              v-model="selectedCells"
              :value="cell.id"
            >
          </td>
          <td>{{ cell.sample_id }}</td>
          <td>{{ cell.cell_type }}</td>
          <td>{{ cell.cell_name }}</td>
          <td>{{ cell.freezer }}</td>
          <td>{{ cell.location }}</td>
          <td style="text-align: right;">{{ cell.quantity }}</td>
          <td>
            <button @click="showOutboundDialog(cell)" class="btn-outbound">
              <i class="el-icon-sold-out"></i> 出库
            </button>
          </td>
        </tr>
      </tbody>
    </table>

    <!-- 分页 -->
    <div class="pagination">
      <span>每页显示：</span>
      <select v-model="pagination.pageSize" @change="handleSizeChange">
        <option value="10">10</option>
        <option value="20">20</option>
        <option value="50">50</option>
      </select>
      <button
        @click="prevPage"
        :disabled="pagination.currentPage === 1"
        class="btn-page"
      >
        上一页
      </button>
      <span>当前页：{{ pagination.currentPage }}</span>
      <button
        @click="nextPage"
        :disabled="pagination.currentPage >= pagination.totalPages"
        class="btn-page"
      >
        下一页
      </button>
      <span>共 {{ pagination.total }} 条记录</span>
    </div>

    <!-- 批量操作 -->
    <div v-if="selectedCells.length > 0" class="bulk-actions">
      <button @click="showBulkOutboundDialog" class="btn-bulk-outbound">
        <i class="el-icon-sold-out"></i> 批量出库 ({{ selectedCells.length }})
      </button>
    </div>

    <!-- 单细胞出库对话框 -->
    <div v-if="showDialog" class="modal-overlay">
      <div class="modal-dialog">
        <h3>细胞出库</h3>
        <div class="modal-content">
          <div class="form-group">
            <label>细胞名称:</label>
            <span>{{ currentCell.cell_name }}</span>
          </div>
          <div class="form-group">
            <label>当前库存:</label>
            <span>{{ currentCell.quantity }}</span>
          </div>
          <div class="form-group">
            <label for="outQuantity">出库数量</label>
            <input
              type="number"
              id="outQuantity"
              v-model.number="outboundForm.quantity"
              :max="currentCell.quantity"
              min="1"
              class="form-input"
            >
          </div>
          <div class="form-group">
            <label for="receiver">接收人</label>
            <input
              type="text"
              id="receiver"
              v-model="outboundForm.receiver"
              required
              class="form-input"
            >
          </div>
          <div class="form-group">
            <label for="purpose">用途</label>
            <input
              type="text"
              id="purpose"
              v-model="outboundForm.purpose"
              class="form-input"
            >
          </div>
          <div class="form-group">
            <label for="notes">备注</label>
            <textarea
              id="notes"
              v-model="outboundForm.notes"
              class="form-input"
            ></textarea>
          </div>
        </div>
        <div class="modal-actions">
          <button @click="cancelOutbound" class="btn-cancel">取消</button>
          <button @click="confirmOutbound" class="btn-confirm">确认出库</button>
        </div>
      </div>
    </div>

    <!-- 批量出库对话框 -->
    <div v-if="showBulkDialog" class="modal-overlay">
      <div class="modal-dialog">
        <h3>批量出库</h3>
        <div class="modal-content">
          <p>将出库 {{ selectedCells.length }} 种细胞</p>
          <div class="form-group">
            <label for="bulkReceiver">接收人</label>
            <input
              type="text"
              id="bulkReceiver"
              v-model="bulkOutboundForm.receiver"
              required
              class="form-input"
            >
          </div>
          <div class="form-group">
            <label for="bulkPurpose">用途</label>
            <input
              type="text"
              id="bulkPurpose"
              v-model="bulkOutboundForm.purpose"
              class="form-input"
            >
          </div>
          <div class="form-group">
            <label for="bulkNotes">备注</label>
            <textarea
              id="bulkNotes"
              v-model="bulkOutboundForm.notes"
              class="form-input"
            ></textarea>
          </div>
        </div>
        <div class="modal-actions">
          <button @click="cancelBulkOutbound" class="btn-cancel">取消</button>
          <button @click="confirmBulkOutbound" class="btn-confirm">确认出库</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data () {
    return {
      cellTypes: [],
      freezers: [],
      // 在 CellOutbound.vue 的 data() 中替换 cells 数组
      cells: [
        {
          id: 1,
          sample_id: 'S20230001',
          cell_type: '脐带间充质干细胞',
          cell_name: 'UC-MSC-001',
          freezer: '超低温冰柜A (No.1)',
          location: 'A区-1层-02柜-抽屉1-箱2-(3,4)',
          quantity: 15,
          entry_time: '2023-05-10T09:30:00Z'
        },
        {
          id: 2,
          sample_id: 'S20230002',
          cell_type: 'NK细胞',
          cell_name: 'NK-2023-002',
          freezer: '液氮罐C (No.3)',
          location: 'C区-3层-05罐-抽屉2-箱1-(1,2)',
          quantity: 8,
          entry_time: '2023-05-12T14:15:00Z'
        },
        {
          id: 3,
          sample_id: 'S20230003',
          cell_type: 'iPSC',
          cell_name: 'iPSC-HDF-003',
          freezer: '超低温冰柜B (No.2)',
          location: 'B区-2层-03柜-抽屉3-箱4-(5,6)',
          quantity: 20,
          entry_time: '2023-05-15T11:20:00Z'
        },
        {
          id: 4,
          sample_id: 'S20230004',
          cell_type: 'HEK293',
          cell_name: 'HEK293T-004',
          freezer: '超低温冰柜A (No.1)',
          location: 'A区-1层-02柜-抽屉2-箱3-(2,3)',
          quantity: 12,
          entry_time: '2023-05-18T16:45:00Z'
        },
        {
          id: 5,
          sample_id: 'S20230005',
          cell_type: 'Hela',
          cell_name: 'Hela-005',
          freezer: '超低温冰柜B (No.2)',
          location: 'B区-2层-03柜-抽屉1-箱2-(4,5)',
          quantity: 6,
          entry_time: '2023-05-20T10:10:00Z'
        }
      ],
      selectedCells: [],
      selectAll: false,
      filters: {
        cellType: '',
        freezer: '',
        searchQuery: ''
      },
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 5,
        totalPages: 1
      },
      showDialog: false,
      showBulkDialog: false,
      currentCell: {},
      outboundForm: {
        quantity: 1,
        receiver: '',
        purpose: '',
        notes: ''
      },
      bulkOutboundForm: {
        receiver: '',
        purpose: '',
        notes: ''
      }
    }
  },
  computed: {
    paginatedData () {
      const start = (this.pagination.currentPage - 1) * this.pagination.pageSize
      const end = start + this.pagination.pageSize
      return this.cells.slice(start, end)
    }
  },
  methods: {
    async loadInitialData () {
      try {
        const [cellTypesRes, freezersRes] = await Promise.all([
          this.$api.get('/api/cell-types/'),
          this.$api.get('/api/freezers/')
        ])
        this.cellTypes = cellTypesRes.data
        this.freezers = freezersRes.data
        this.searchCells()
      } catch (error) {
        console.error('加载初始数据失败:', error)
      }
    },
    async searchCells () {
      try {
        const params = {
          page: this.pagination.currentPage,
          page_size: this.pagination.pageSize
        }

        if (this.filters.cellType) {
          params.cell_type = this.filters.cellType
        }

        if (this.filters.freezer) {
          params.freezer = this.filters.freezer
        }

        if (this.filters.searchQuery) {
          params.search = this.filters.searchQuery
        }

        const res = await this.$api.get('/api/samples/', { params })
        this.cells = res.data.results
        this.pagination.total = res.data.count
        this.pagination.totalPages = Math.ceil(res.data.count / this.pagination.pageSize)
      } catch (error) {
        console.error('搜索细胞失败:', error)
      }
    },
    toggleSelectAll () {
      if (this.selectAll) {
        this.selectedCells = this.paginatedData.map(cell => cell.id)
      } else {
        this.selectedCells = []
      }
    },
    showOutboundDialog (cell) {
      this.currentCell = { ...cell }
      this.outboundForm = {
        quantity: 1,
        receiver: '',
        purpose: '',
        notes: ''
      }
      this.showDialog = true
    },
    showBulkOutboundDialog () {
      this.bulkOutboundForm = {
        receiver: '',
        purpose: '',
        notes: ''
      }
      this.showBulkDialog = true
    },
    cancelOutbound () {
      this.showDialog = false
    },
    cancelBulkOutbound () {
      this.showBulkDialog = false
    },
    async confirmOutbound () {
      if (!this.outboundForm.receiver) {
        this.$message.error('请输入接收人')
        return
      }

      try {
        const payload = {
          sample_id: this.currentCell.id,
          quantity: this.outboundForm.quantity,
          receiver: this.outboundForm.receiver,
          purpose: this.outboundForm.purpose,
          notes: this.outboundForm.notes
        }

        await this.$api.post('/api/outbounds/', payload)
        this.$message.success(`出库成功: ${this.currentCell.cell_name} x${this.outboundForm.quantity}`)
        this.showDialog = false
        this.searchCells()
      } catch (error) {
        console.error('出库失败:', error)
        this.$message.error('出库失败: ' + (error.response?.data?.message || error.message))
      }
    },
    async confirmBulkOutbound () {
      if (!this.bulkOutboundForm.receiver) {
        this.$message.error('请输入接收人')
        return
      }

      try {
        const payload = {
          sample_ids: this.selectedCells,
          receiver: this.bulkOutboundForm.receiver,
          purpose: this.bulkOutboundForm.purpose,
          notes: this.bulkOutboundForm.notes
        }

        await this.$api.post('/api/outbounds/bulk/', payload)
        this.$message.success(`批量出库成功: ${this.selectedCells.length} 种细胞`)
        this.showBulkDialog = false
        this.selectedCells = []
        this.selectAll = false
        this.searchCells()
      } catch (error) {
        console.error('批量出库失败:', error)
        this.$message.error('批量出库失败: ' + (error.response?.data?.message || error.message))
      }
    },
    prevPage () {
      if (this.pagination.currentPage > 1) {
        this.pagination.currentPage--
        this.searchCells()
      }
    },
    nextPage () {
      if (this.pagination.currentPage < this.pagination.totalPages) {
        this.pagination.currentPage++
        this.searchCells()
      }
    },
    handleSizeChange () {
      this.pagination.currentPage = 1
      this.searchCells()
    }
  },
  mounted () {
    this.loadInitialData()
  }
}
</script>

<style scoped>
.filter-bar {
  display: flex;
  flex-wrap: wrap;
  gap: 16px 24px;
  margin-bottom: 24px;
  align-items: center;
}

.filter-item {
  display: flex;
  align-items: center;
  gap: 8px;
  min-width: 220px;
}

.filter-item label {
  min-width: 60px;
  font-weight: 500;
  white-space: nowrap;
}

.filter-item select,
.filter-item input[type="text"] {
  padding: 6px 12px;
  border: 1px solid #ced4da;
  border-radius: 4px;
  font-size: 14px;
  flex: 1;
  min-width: 120px;
}

.btn-search {
  padding: 6px 12px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  display: inline-flex;
  align-items: center;
  gap: 5px;
}

.btn-search:hover {
  background-color: #0069d9;
}

.storage-table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 16px;
  background-color: #fff;
  box-shadow: 0 1px 5px rgba(0, 0, 0, 0.05);
}

.storage-table thead {
  background-color: #f1f3f5;
}

.storage-table th,
.storage-table td {
  padding: 12px 16px;
  text-align: left;
  border-bottom: 1px solid #dee2e6;
}

.storage-table tbody tr:hover {
  background-color: #f8f9fa;
}

.btn-outbound {
  padding: 6px 12px;
  background-color: #dc3545;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  display: inline-flex;
  align-items: center;
  gap: 5px;
}

.btn-outbound:hover {
  background-color: #c82333;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 12px;
  font-size: 14px;
}

.pagination select {
  padding: 4px 8px;
  border-radius: 4px;
  border: 1px solid #ced4da;
}

.btn-page {
  padding: 6px 12px;
  border: 1px solid #ced4da;
  background-color: white;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.btn-page:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.bulk-actions {
  margin-top: 20px;
  text-align: right;
}

.btn-bulk-outbound {
  padding: 8px 16px;
  background-color: #dc3545;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  display: inline-flex;
  align-items: center;
  gap: 5px;
}

.btn-bulk-outbound:hover {
  background-color: #c82333;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-dialog {
  background-color: white;
  border-radius: 8px;
  width: 500px;
  max-width: 90%;
  padding: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.modal-dialog h3 {
  margin-top: 0;
  text-align: center;
  color: #333;
}

.modal-content {
  margin-bottom: 20px;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: 500;
}

.form-input {
  width: 90%;
  padding: 8px 12px;
  border: 1px solid #ced4da;
  border-radius: 4px;
  font-size: 14px;
}

textarea.form-input {
  min-height: 80px;
}
.cell-storage-form {
  padding: 24px;
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
}
.modal-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.btn-cancel,
.btn-confirm {
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.btn-cancel {
  background-color: #6c757d;
  color: white;
  border: none;
}

.btn-cancel:hover {
  background-color: #5a6268;
}

.btn-confirm {
  background-color: #28a745;
  color: white;
  border: none;
}

.btn-confirm:hover {
  background-color: #218838;
}
</style>
